'''
Created on Feb 18, 2010

@author: steveno
'''

'''
MapControl in een panel in een frame
'''
from wx import wx
import threading, time
from BruTile.BruTile import BruTile
from GUIHandler import GUIHandler
from TileSeeder.PropertiesScreen import PropertiesScreen

ID_TEXTCTRL = 10000
ID_BUTTON = 10001
ID_LISTBOX = 10002
ID_FOREIGN = 10003
ID_CHECKBOX = 10004
ID_SLIDER = 10005
ID_GAUGE = 10006
ID_TEXT = 10007

class MainFrame(wx.Frame):
    """Main Frame holding the Panel."""
    
    showTileSeeder = None
    
    guiHandler = None
    tileSeederWindow = None
    
    width = 0
    height = 0

    def __init__(self, parent, title, call_fit = True, set_sizer = True ):
        """Create the DemoFrame."""
        threading.current_thread().setName("GUI")
        
        wx.Frame.__init__(self,parent, title=title, size=wx.DisplaySize())

        panel = wx.Panel(self)
        
        self.guiHandler = GUIHandler()
        # Build the menu bar
        self.width = self.GetClientSize()[0]
        self.height = self.GetClientSize()[1]
        self.bindMenu()
        self.initValues(panel)
        # Create a statusbar
        self.CreateStatusBar()
        
        # FlexGridsizer to contain everything (item0)
        sizerMain = wx.FlexGridSizer( 0, 2, 0, 0 )
        
        # Box sizer with the information of the tile cache server (item2)
        boxTilecache = wx.StaticBox(panel, -1, "Tilecache" )     
        
        #item1  
        sizerTilecache = wx.StaticBoxSizer( boxTilecache, wx.HORIZONTAL )
        
        # Flex sizer within the TileCache box sizer (item3)
        sizerFlexTC = wx.FlexGridSizer( 0, 1, 0, 0 )
    
        #item4 
        sizerBoxTC_v = wx.BoxSizer( wx.VERTICAL )
        
        #item5
        sizerBoxTC_h = wx.BoxSizer( wx.HORIZONTAL )
        
        # URL field for tilecache capabilities (item6)
        
        sizerBoxTC_h.Add( self.guiHandler.txtTCUrl, 0, wx.ALIGN_CENTER|wx.ALL, 5 )
        
        # Button to load the tilecache capabilities (item7)
        btnTCLoad = wx.Button( panel, ID_BUTTON, "Load", wx.DefaultPosition, wx.DefaultSize, 0 )
        btnTCLoad.Bind(wx.EVT_BUTTON, self.onBtnLoadClick)
        sizerBoxTC_h.Add( btnTCLoad, 0, wx.ALIGN_CENTER|wx.ALL, 5 )
        
        sizerBoxTC_v.Add( sizerBoxTC_h, 0, wx.ALIGN_CENTER|wx.ALL, 5 )
        
        #listbox to show the list of layers  (item8)
        
        sizerBoxTC_v.Add( self.guiHandler.lboxTC, 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 10 )
        
        sizerBoxTC_h2 = wx.BoxSizer( wx.HORIZONTAL )
        
        # URL field for tilecache capabilities (item6)
        btn_cancel = wx.Button( panel, wx.ID_CANCEL,  "Clear list selection", wx.DefaultPosition, wx.DefaultSize, 0)
        btn_cancel.Bind(wx.EVT_BUTTON, self.btnClearListSelection)
        sizerBoxTC_h2.Add( btn_cancel, 0, wx.ALIGN_CENTER, 5 )
        # Button to load the tilecache capabilities (item7)
        btn_cancel = wx.Button( panel, wx.ID_CANCEL,  "Load TileSeed", wx.DefaultPosition, wx.DefaultSize, 0)
        btn_cancel.Bind(wx.EVT_BUTTON, self.btnLoadTileSeed)
        sizerBoxTC_h2.Add( btn_cancel, 0, wx.ALIGN_CENTER, 5 )

        sizerBoxTC_v.Add(sizerBoxTC_h2)
        sizerFlexTC.Add( sizerBoxTC_v, 0, 0, 5 )
        sizerTilecache.Add( sizerFlexTC, 0, wx.ALIGN_CENTER_HORIZONTAL, 5 )
        sizerMain.Add( sizerTilecache, 0, wx.ALL, 5 )
        sizerMain.Add( self.guiHandler.map, 0, wx.GROW|wx.ALIGN_RIGHT|wx.ALL, 5 )
        self.Bind(wx.EVT_MOUSEWHEEL, self.guiHandler.map.map_control.mouse_handler.onScrollwheel)
    
        sizerMain.AddGrowableCol(1)
    
        sizerMain.AddGrowableRow(0)

        self.SetAutoLayout(True)
        if set_sizer == True:
            self.SetSizer(sizerMain)
            if call_fit == True:
                sizerMain.SetSizeHints( self )
        self.SetMinSize([400,400])
        
        self.Show(True)
        
    def getValues(self):
        return (self.guiHandler.labelMinX,self.guiHandler.labelMinY,self.guiHandler.labelMaxX, self.guiHandler.labelMaxY, self.guiHandler.lboxZoomLevels)
    
    def initValues(self, panel):
        self.guiHandler.txtTCUrl = wx.TextCtrl( panel, ID_TEXTCTRL, "http://t1.edugis.nl/tiles/", wx.DefaultPosition, [80,-1], 0 )
        self.guiHandler.txtTCUrl.SetToolTip( wx.ToolTip("Enter URL to a TMS capabilities doc") )
        
        self.guiHandler.lboxTC = wx.ListBox( panel, ID_LISTBOX, wx.DefaultPosition, [80,500], [""] , wx.LB_MULTIPLE )
        self.guiHandler.lboxTC.Clear()
        
        #Terug zetten
        self.guiHandler.map = BruTile(panel,wx.ID_ANY, 500, 600)
        #self.guiHandler.map = BruTile(panel,wx.ID_ANY, self.width, self.height)
    
    def bindMenu(self):
        wx.EVT_MENU(self, wx.ID_EXIT,  self.OnQuit)
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        '''
        MenuBar = wx.MenuBar()
        FileMenu = wx.Menu()
        TileSeedMenu = wx.Menu()
        
        saveMenuItem = FileMenu.Append(wx.ID_SAVEAS, text="&Save")
        openMenuItem = FileMenu.Append(wx.ID_OPEN, text="&Open")
        FileMenu.AppendSeparator()
        quitMenuItem = FileMenu.Append(wx.ID_EXIT, text="&Quit")

        startMenuItem = TileSeedMenu.Append(wx.ID_OK, text="&Start caching")
        pauseMenuItem = TileSeedMenu.Append(wx.ID_EXIT, text="&Pause caching")
        cancelMenuItem = TileSeedMenu.Append(wx.ID_EXIT, text="&Cancel caching")
        TileSeedMenu.AppendSeparator()
        propertiesMenuItem = TileSeedMenu.Append(wx.ID_PROPERTIES, text="&Properties")
        
        self.Bind(wx.EVT_MENU, self.OnSave, saveMenuItem)
        self.Bind(wx.EVT_MENU, self.OnOpen, openMenuItem)
        
        self.Bind(wx.EVT_MENU, self.OnStart, startMenuItem)
        self.Bind(wx.EVT_MENU, self.OnPause, pauseMenuItem)
        self.Bind(wx.EVT_MENU, self.OnCancel, cancelMenuItem)
        self.Bind(wx.EVT_MENU, self.OnTileSeedProperties, propertiesMenuItem)

        
        
        MenuBar.Append(FileMenu, "&File")
        MenuBar.Append(TileSeedMenu, "&TileSeed")
        self.SetMenuBar(MenuBar)
        '''
    def updateSeedExtent(self, extent):
        if not self.tileSeederWindow is None:
            return self.tileSeederWindow.pHandler.UpdateSeedExtent(extent)
        else:
            return None

    def updateSeedList(self, event):
        if not self.tileSeederWindow is None:
            if self.guiHandler.lboxTC.IsSelected(event.Selection):
                self.tileSeederWindow.pHandler.pEvents.AddSeedToList(event)
            else:
                if not self.tileSeederWindow.pHandler.pEvents.IsTileSeedActive(event.ClientData):
                    self.tileSeederWindow.pHandler.pEvents.RemoveSeedFromList(event.ClientData)
                else:
                    self.guiHandler.lboxTC.Select(event.Selection)        
    
    def setTileSeederWindow(self, window):
        self.tileSeederWindow = window
        self.guiHandler.map.map_control.updateSeedInfo = self.updateSeedExtent
        self.guiHandler.lboxTC.Bind(wx.EVT_LISTBOX, self.updateSeedList)
    
    def btnClearListSelection(self, event):
        for i in range(0, len(self.guiHandler.lboxTC.Items)):
            if (self.guiHandler.lboxTC.IsSelected(i)) and not self.tileSeederWindow is None:
                item = self.guiHandler.lboxTC.GetClientData(i)
                self.tileSeederWindow.removeSeedFromList(item)
                if not(self.tileSeederWindow.layer_handler.isTileSeedActive(item.tile_schema.name)):
                    self.guiHandler.lboxTC.Deselect(i)
            else:
                self.guiHandler.lboxTC.Deselect(i)
    
    def OnTileSeedProperties(self, event):
        tile_seed = self.guiHandler.lboxTC.GetClientData(self.guiHandler.lboxTC.GetSelection())[1]
        self.showTileSeeder(tile_seed.href,tile_seed)
    
    def deSelectLayer(self, name):
        for i in range(0, len(self.guiHandler.lboxTC.Items)):
            layer = self.guiHandler.lboxTC.Items[i]
            if (name == layer):
                self.guiHandler.lboxTC.Deselect(i)

    def btnLoadTileSeed(self, event):
        seeds = []
        selections = []
        if (self.guiHandler.seedIsSelected()):
            selections = self.guiHandler.lboxTC.GetSelections()
            
            for selection in selections:
                seeds.append(self.guiHandler.lboxTC.GetClientData(selection))
                
            self.showTileSeeder(seeds)
    
    def onBtnCancelClick(self, event):
        print("GUI: Cancel")
        tile_seed = self.guiHandler.lboxTC.GetClientData(self.guiHandler.lboxTC.GetSelection())
        self.guiHandler.tile_seeder.quitTileSeed(tile_seed)
    
    def onBtnApplyClick(self, event):
        self.guiHandler.onApplyHandler()

    def onBtnLoadClick(self, event):
        self.guiHandler.onLoadHandler(self.tileSeederWindow is None)
        
    def OnSave(self, event=None):
        fileLocation = self.fileDialog("Save seed", wx.SAVE)
        self.guiHandler.fileSaveHandler(fileLocation)
            
    def OnOpen(self, event=None):
        fileLocation = self.fileDialog("Open seed", wx.OPEN)
        print(fileLocation)
    
    def fileDialog(self, message, function):
        filters = 'Seed files (*.seed)|*.seed|All files (*.*)|*.*'

        dialog = wx.FileDialog ( None, message = message, wildcard = filters, style = function )
        
        if dialog.ShowModal() == wx.ID_OK:
            directory = dialog.GetDirectory()
            fileName = dialog.GetFilename()
            return (directory, fileName)
        else:
            print 'Cancel'
        
        dialog.Destroy()
    
    def clearTileSeederWindow(self):
        self.tileSeederWindow = None
        self.guiHandler.map.map_control.clearExtents()
    
    def OnClose(self, event=None):
        if not(self.tileSeederWindow is None):
            self.tileSeederWindow.pHandler.pEvents.OnQuit(None)
        
        self.guiHandler.map.shut_down()

        for t in threading.enumerate():
            print("Thread: "+t.getName())

        print("GUI: OnClose")
        self.Destroy()
    
    def OnQuit(self, event=None):
        if not(self.tileSeederWindow is None):
            self.tileSeederWindow.OnQuit()

        self.guiHandler.map.shut_down()
        
        for t in threading.enumerate():
            print("Thread: "+t.getName())
        
        print("GUI: OnQuit")
        self.Destroy()

class MyApp(wx.App):
    
    mainFrame = None
    #windows = []
    
    def OnInit(self):
        self.mainFrame = MainFrame(None, title="TileSeeder")
        #self.mainFrame.closeWindows = self.OnQuit
        self.mainFrame.Show(True)
        
        self.SetTopWindow(self.mainFrame)
        
        self.mainFrame.showTileSeeder = self.OpenTileSeeder
        return True
    
    def OpenTileSeeder(self, seeds):
        if (self.mainFrame.tileSeederWindow is None):
            propertyWindow = PropertiesScreen(None, -1, "TileSeeder")
            
            propertyWindow.pHandler.UpdateMainWindow = self.mainFrame.clearTileSeederWindow
            propertyWindow.pHandler.SetSeedExtent = self.mainFrame.guiHandler.map.map_control.setSeedExtent
            propertyWindow.pHandler.SetLayerExtent = self.mainFrame.guiHandler.map.map_control.setLayerExtent
            propertyWindow.pHandler.UpdateMainWindowList = self.mainFrame.guiHandler.DeselectLayer
            #propertyWindow.inProcess = self.mainFrame.guiHandler.map.map_control.setInProcess
            
            propertyWindow.deselect = self.mainFrame.deSelectLayer
            propertyWindow.pHandler.AddTileLayers(seeds)
            self.mainFrame.setTileSeederWindow(propertyWindow)

app = MyApp(0)
app.MainLoop()
'''
if __name__ == '__main__':
    app = wx.App(redirect=False)
    frame = MainFrame(None, title="TileSeeder")
    #BruTile(frame,wx.ID_ANY)
    app.MainLoop()'''